<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="填表时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="经办人" prop="propose" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择经办人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="经办部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择经办部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">汇款信息</view>
        <u-form-item label="汇款单位名称" prop="remittanceUnit" required>
          <h-select-customer-input
            style="width: 100%"
            v-model="model.remittanceUnit"
            commercialType="1"
            border="surround"
            placeholder="请选择业主单位"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.remittanceUnit"
          ></h-select-customer-input>
        </u-form-item>
        <u-form-item label="汇款日期" prop="remittanceDate" required>
          <h-time-select
            mode="date"
            ref="remittanceDate"
            v-model="model.remittanceDate"
            placeholder="请选择汇款日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="汇款金额" prop="remittanceAmount" required>
          <h-money-input placeholder="请输入汇款金额" v-model="model.remittanceAmount"></h-money-input>
          <!-- <u--input type="number" v-number-normal placeholder="请输入汇款金额" v-model="model.remittanceAmount"></u--input> -->
        </u-form-item>
        <u-form-item label="支付方式" prop="payMode" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.payMode"
            objectField="model.payMode"
            placeholder="请选择支付方式"
            border="surround"
            dictName="collect_money_mode"
            @change="radioModeChange"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="收款单位名称" prop="payeeUnit" required>
          <!-- <h-select-company-input
            style="width: 100%"
            v-model="model.payeeUnit"
            border="surround"
            placeholder="请选择公司"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.payeeUnit"
            @input="resetMetaData"
          ></h-select-company-input> -->
					<h-select-company-input-popup
					  style="width: 100%"
					  v-model="model.payeeUnit"
					  placeholder="请选择公司"
					  border="surround"
						@back="resetMetaData"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
					></h-select-company-input-popup>
        </u-form-item>
				<template v-if="model.payMode == '1'">
				  <u-form-item label="收款银行" prop="bankName" required>
				    <u--input v-model="model.bankName" placeholder="请输入收款银行"></u--input>
				  </u-form-item>
				  <u-form-item label="收款账户" prop="payeeAccountNo" required>
				    <u--input v-model="model.payeeAccountNo" placeholder="请输入收款账户"></u--input>
				  </u-form-item>
				</template>
        <u-form-item label="备注" prop="remark">
          <u--textarea v-model="model.remark" :confirm-type="null" maxlength="500" count placeholder="请输入备注"></u--textarea>
        </u-form-item>
      </view>

      <div class="basic-style">
        <view class="basic-title basic-border">认领信息</view>
        <u-form-item label="认领人" prop="remark">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.employeeId"
            placeholder="请选择认领人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.employeeId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="是否为保证金" prop="isDeposit" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.isDeposit"
            objectField="model.isDeposit"
            placeholder="请选择是否为保证金"
            border="surround"
            dictName="is_deposit"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						@change="radioIsDepositChange"
          ></h-select-input-tag>
        </u-form-item>
      </div>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachments" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>
      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
    </u-form>
    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, edit, info, queryResultByTenderId } from '@/api/finance/ErpFinanceCollectMoneyApplicationBillForm'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import fileList from '@/pages/synergy/components/fileList.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗

export default {
  name: 'ErpFinanceProjectDepositBillForm',
  components: { fileList, ProcessNodeConfiguration },
  data() {
    return {
      backUpApplicant: '',
      backUpTeamId: '',
      isReset: false,
      isSubmit: false,
      resetKey: '',
      index: null,
      // showFormModal: false,
      // confirmModal: false,
      loading: false,
      id: '',
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        billNo: '',
        proposer: '',
        proposerDeptId: '',
        createTime: '',
        // 基本信息 - 非公用
        remittanceUnit: '',
        remittanceDate: '',
        remittanceAmount: '',
        payMode: '',
        payeeUnit: '',
        remark: '',
        bankName: '',
        payeeAccountNo: '',
        // 禁用的字段
        employeeId: '',
        isDeposit: '',
        // 附件
        attachments: null,
      },
      formData: [],
      rules: {
        billNo: [
          {
            required: true,
            message: '请输入单据编号!',
            trigger: ['blur', 'change'],
          },
        ],
        proposerDeptId: [
          {
            required: true,
            message: '请选择经办部门!',
            trigger: ['blur', 'change'],
          },
        ],
        proposer: [
          {
            required: true,
            message: '请选择经办人!',
            trigger: ['blur', 'change'],
          },
        ],
        createTime: [
          {
            required: true,
            message: '请选择填表时间!',
            trigger: ['blur', 'change'],
          },
        ],
        bpmBizTitle: [{ required: true, message: '请输入流程标题!', trigger: ['blur', 'change'] }],
        remittanceUnit: [{ required: true, message: '请选择汇款单位!', trigger: ['blur', 'change'] }],
        remittanceDate: [{ required: true, message: '请选择汇款时间!', trigger: ['blur', 'change'] }],
        remittanceAmount: [
          {
            required: true,
            pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
            message: '请输入汇款金额!',
            trigger: ['blur', 'change'],
          },
        ],
        payeeUnit: [{ required: true, message: '请选择收款单位!', trigger: ['blur', 'change'] }],
        payeeAccountNo: [{ required: true, message: '请输入收款账户!', trigger: ['blur', 'change'] }],
        bankName: [{ required: true, message: '请输入收款银行!', trigger: ['blur', 'change'] }],
        // isDeposit: [
        //     { required: true, message: '请选择是否是保证金!'},
        // ],
        depositBillId: [{ required: true, message: '请选择保证金申请单!', trigger: ['blur', 'change'] }],
        interestAmount: [
          {
            required: true,
            pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
            message: '请输入利息金额!',
            trigger: ['blur', 'change'],
          },
        ],
        payMode: [{ required: true, message: '请选择支付方式!', trigger: ['blur', 'change'] }],
        isDeposit: [{ required: true, message: '请选择是否为保证金!', trigger: ['blur', 'change'] }],
      },
      flowCode: 'onl_erp_finance_collect_money_application_bill',
      formUrl: '/erp/finance/collectMoney/modules/ErpFinanceCollectMoneyApplicationBillForm',
      beanName: 'erpFinanceCollectMoneyApplicationBillServiceImpl',
      formUrlMobile: '/pages/synergy/collectMoneyApplicationBill',
      dictOptions: {},
      processId: '1521814569456091137',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
    this.initDicts()
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
  },
  methods: {
    radioModeChange(val) {
      this.$set(this.model, 'bankName', '')
      this.$set(this.model, 'payeeAccountNo', '')
    },
    resetMetaData(data) {
			if(data && this.model.payMode == '1'){
				this.$set(this.model,'payeeAccountNo',data.bankAccountNo)
				this.$set(this.model,'bankName',data.bankName)
			} else {
				this.$set(this.model,'payeeAccountNo', '')
				this.$set(this.model,'bankName','')
			}
    },
		radioIsDepositChange (val) {
			this.$set(this.model, 'depositBillId', null);
			this.$set(this.model, 'depositRemittanceAmount', '');
			this.$set(this.model, 'feeCategory', null);
			this.$set(this.model, 'itemList', []);
		},
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ proposer: this.userInfo.empId })
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      this.model.payee = this.userInfo.empId //领款人
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
    },
    initDicts() {
      // 汇款单位
      initDictOptions('erp_purchase_supplier,enterprise_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'supplier', res.result)
        }
      })
    },
    validateForm() {
      return this.$refs.form.validate()
    },
    getCreateTime() {
      let createTime = this.model.createTime
      let date = createTime.substring(0, 10)
      return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
    },
    setBpmBizTitle() {
      let createTime = this.getCreateTime()
      let remittanceUnitName = filterMultiDictText(this.dictOptions['supplier'], this.model.remittanceUnit + '')
      //迭代16.7 申请人-申请日期（年月日）- 汇款单位名称 -金额（汇款金额）
      this.model.bpmBizTitle =
        this.userInfo?.employee?.name + ' - ' + createTime + (this.model.remittanceUnit ? ' - ' + remittanceUnitName:'') + (this.model.remittanceAmount ? ' - ' + this.model.remittanceAmount : '')  //标题
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.isSubmit = true
          if (this.id) {
            await this.getProcessList(this.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              await this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home',
                })
              }
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },
  },
  watch: {
    'model.applicant'(current, old) {
      if (old && current && old !== current) {
        this.backUpApplicant = old
        // this.resetMetaData()
      }
    },
    'model.teamId'(current, old) {
      if (old && current && old !== current) {
        this.backUpTeamId = old
        // this.resetMetaData()
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
